package com.liuda.workbench.controller;

import com.liuda.commons.constants.Constants;
import com.liuda.commons.domain.ReturnObject;
import com.liuda.commons.function.ActivityFunction;
import com.liuda.commons.utils.DateUtil;
import com.liuda.commons.utils.UUIDUtil;
import com.liuda.settings.domain.User;
import com.liuda.settings.service.UserService;
import com.liuda.workbench.domain.Activity;
import com.liuda.workbench.domain.ActivityRemark;
import com.liuda.workbench.service.ActivityRemarkService;
import com.liuda.workbench.service.ActivityService;
import com.liuda.workbench.service.impl.ActivityServiceImpl;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

@Controller
public class ActivityController {
    @Autowired
    UserService userService;
    @Autowired
    ActivityService activityService;
    @Autowired
    ActivityRemarkService activityRemarkService;

    @RequestMapping("/workbench/activity/index.do")
    public String activityMain(HttpServletRequest request) {
        List<User> users = userService.getAllUnlockedUsers();
        request.setAttribute("users", users);
        return "workbench/activity/index";
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/createActivity.do")
    public Object createActivity(Activity activity, HttpServletRequest request) {
        ReturnObject returnObject = new ReturnObject();
        User user = (User) request.getSession().getAttribute(Constants.SESSION_USER);
        activity.setCreateBy(user.getId());
        activity.setId(UUIDUtil.createId());
        activity.setCreateTime(DateUtil.formatDateTime(new Date()));
        int count = activityService.createActivity(activity);
        if (count > 0) {
            returnObject.setState(Constants.RETURN_OBJECT_SUCCESS);
        } else {
            returnObject.setState(Constants.RETURN_OBJECT_FAILURE);
            returnObject.setMsg("系统忙，请稍后重试...");
        }
        return returnObject;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/queryByCondition.do")
    public Object queryActivityByCondition(String name, String owner, String startDate, String endDate, int pageSize, int pageNo) {
        Map map = new HashMap();
        map.put("name", name);
        map.put("owner", owner);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        int startRow = (pageNo - 1) * pageSize;
        map.put("pageSize", pageSize);
        map.put("startRow", startRow);
        int count = activityService.queryCountOfActivityByCondition(map);
        List<Activity> activityList = activityService.queryActivityByCondition(map);
        Map returnMap = new HashMap();
        returnMap.put("totalRows", count);
        returnMap.put("activityList", activityList);
        return returnMap;
    }

    @RequestMapping("/workbench/activity/deleteByIds.do")
    @ResponseBody
    public Object deleteByIds(String[] ids) {
        ReturnObject object = new ReturnObject();
        try {
            int count = activityService.deleteByIds(ids);
            if (count <= 0) {
                object.setState(Constants.RETURN_OBJECT_FAILURE);
                object.setMsg("系统忙，请稍后......");
            } else {
                object.setState(Constants.RETURN_OBJECT_SUCCESS);
            }
        } catch (Exception e) {
            object.setState(Constants.RETURN_OBJECT_FAILURE);
            object.setMsg("系统忙，请稍后......");
        }
        return object;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/queryActivityById.do")
    public Object queryActivityById(String id) {
        return activityService.queryActivityById(id);
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/updateById.do")
    public Object updateById(Activity activity, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(Constants.SESSION_USER);
        activity.setEditBy(user.getId());
        activity.setEditTime(DateUtil.formatDateTime(new Date()));
        ReturnObject object = new ReturnObject();
        int count = activityService.updateById(activity);
        if (count == 1) {
            object.setState(Constants.RETURN_OBJECT_SUCCESS);
        } else {
            object.setState(Constants.RETURN_OBJECT_FAILURE);
            object.setMsg("系统忙，请稍后...");
        }
        return object;
    }

    @RequestMapping("/workbench/activity/downAllActivity.do")
    public void downAllActivity(HttpServletResponse response) throws Exception {
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=activityList.xls");
        List<Activity> activityList = activityService.selectAll();
        Workbook wb= ActivityFunction.createWorkBook(activityList);
        OutputStream ops = response.getOutputStream();
        wb.write(ops);
        ops.flush();
        wb.close();
    }
    @RequestMapping("/workbench/activity/downActivityByChoice.do")
    public void downActivityByChoice(HttpServletResponse response,String[] ids) throws Exception{
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=chooseActivityList.xls");
        List<Activity> activityList = activityService.selectByIds(ids);
        Workbook wb= ActivityFunction.createWorkBook(activityList);
        OutputStream ops = response.getOutputStream();
        wb.write(ops);
        ops.flush();
        wb.close();
    }
    @ResponseBody
    @RequestMapping("/workbench/activity/importActivity.do")
    public Object importActivity(MultipartFile activityFile, HttpSession session) throws Exception{
        HSSFWorkbook wk=new HSSFWorkbook(activityFile.getInputStream());
        HSSFSheet sheet = wk.getSheetAt(0);
        List<Activity> activityList=new ArrayList<>();
        HSSFRow row;
        for (int i = 1; i <=sheet.getLastRowNum(); i++) {
            Activity activity=new Activity();
            activity.setId(UUIDUtil.createId());
            User user=(User)session.getAttribute(Constants.SESSION_USER);
            activity.setOwner(user.getId());
            activity.setCreateBy(user.getId());
            activity.setCreateTime(DateUtil.formatDateTime(new Date()));
            row= sheet.getRow(i);
            activity.setName(ActivityFunction.getHSSFCellValue(row.getCell(Constants.IMPORT_ACTIVITY_NAME_INDEX)));
            activity.setStartDate(ActivityFunction.getHSSFCellValue(row.getCell(Constants.IMPORT_ACTIVITY_START_DATE_INDEX)));
            activity.setEndDate(ActivityFunction.getHSSFCellValue(row.getCell(Constants.IMPORT_ACTIVITY_END_DATE_INDEX)));
            activity.setCost(ActivityFunction.getHSSFCellValue(row.getCell(Constants.IMPORT_ACTIVITY_COST_INDEX)));
            activity.setDescription(ActivityFunction.getHSSFCellValue(row.getCell(Constants.IMPORT_ACTIVITY_DESCRIPTION_INDEX)));
            activityList.add(activity);
        }
        int count=0;
        if(!activityList.isEmpty()) {
            count=activityService.insertActivities(activityList);
        }
        ReturnObject object=new ReturnObject();
        if(count>0){
            object.setState(Constants.RETURN_OBJECT_SUCCESS);
            object.setMsg(count+"");
        }else{
            object.setState(Constants.RETURN_OBJECT_FAILURE);
            object.setMsg("系统忙，导入数据失败!");
        }
        return object;
    }
    @RequestMapping("/workbench/activity/toActivityDetails.do")
    public String toActivityDetails(String activityId,HttpServletRequest request){
        Activity activity=activityService.queryActivityDetailById(activityId);
        List<ActivityRemark> activityRemarkList=activityRemarkService.queryRemarksByActivityId(activityId);
        request.setAttribute("activityRemarkList",activityRemarkList);
        request.setAttribute("activity",activity);
        return "workbench/activity/detail";
    }
    @ResponseBody
    @RequestMapping("/workbench/activity/queryActivityNotInClueId.do")
    public Object queryActivityNotInClueId(String clueId){
        List<Activity> activityList=activityService.queryActivityNotInClueId(clueId);
        return activityList;
    }
    @ResponseBody
    @RequestMapping("/workbench/activity/queryActivityByLikeAndNotInClueId.do")
    public Object queryActivityByLikeAndNotInClueId(String name,String clueId){
        List<Activity> activityList=activityService.queryActivityByLikeAndNotInClueId(name,clueId);
        return activityList;
    }
    @ResponseBody
    @RequestMapping("/workbench/activity/queryActivityByLikeAndClueId.do")
    public Object queryActivityByLike(String name,String clueId){
        List<Activity> activityList=activityService.queryActivityByLikeAndClueId(name,clueId);
        return activityList;
    }
    @ResponseBody
    @RequestMapping("/workbench/activity/queryByLikeForDetail.do")
    public Object queryByLikeForDetail(String name){
        List<Activity> activityList=activityService.selectByLikeForDetail(name);
        return activityList;
    }
}
